package com.example.menuvirtualclient.repository;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.example.menuvirtualclient.core.*;
import com.example.menuvirtualclient.data.Repository;

public class TableRepository extends Repository<Table>{

	private static final String LOGTAG = "TableRepository";
	
	public TableRepository(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	@Override
	public String getTableName() {
		return "Tables";
	}
		
	public Table GetByName(String name) {
		SQLiteDatabase db = null;
		Table entity = null;
		String[] filter = new String[1];
		filter[0] = name;
		//filter[0] = Integer.toString(3);
		try{
			if(!_session.IsOpen())
				_session.Open();
			
			db = _session.Connection();			
			Cursor cursor = db.rawQuery("SELECT id, name, status FROM Tables WHERE name = ?", filter);
			//Cursor cursor = db.rawQuery("SELECT id, name, status FROM Tables WHERE id = ?", filter);
			
			cursor.moveToFirst();
			if(cursor.getCount() > 0){
				entity = BuildNewEntity(cursor);
			}
			cursor.close();
		    db.close();
		}
		catch(Exception ex){
			Log.e(LOGTAG, ex.getMessage());			
		}
		finally{
			if(db != null)
				if(db.isOpen()) {
					db.close();
					Log.e(LOGTAG, "Close database");		
				}
		}
		return entity;
	}
	
	@Override
	public Table BuildNewEntity(Cursor cursor) {
		Table table = new Table();
		table.setId(cursor.getInt(0));
		table.setName(cursor.getString(1));
		table.setStatus(cursor.getInt(2));

		return table;
	}
	
}
